import '../public/index'
import url from '../data/url'
import request from '../data/request'
import {tableConfig, header} from '../data/config'
import {getUrlParam} from '../data/util'
import store from 'store'

const base                = url.base,
      getReportDetailList = request.getReportDetailList,
      getChannelList      = request.getChannelList,
      getDeveloperList    = request.getDeveloperList,
      getBuildingList     = request.getBuildingList

let table,
    jumpData         = {},
    processStatusS   = getUrlParam('processStatusS'),
    propertyId       = getUrlParam('propertyId'),
    operateStartDate = getUrlParam('operateStartDate'),
    operateEndDate   = getUrlParam('operateEndDate'),
    testFlag         = getUrlParam('testFlag'),
    developerId      = getUrlParam('developerId');

if( developerId ){
  $('#operateStartDate').val(operateStartDate)
  $('#operateEndDate').val(operateEndDate)
  $('#testFlag').find(`option[value=${ testFlag }]`).prop('selected','selected');
  jumpData ={
    processStatusS: processStatusS ? processStatusS : '',
    propertyId: propertyId ? propertyId : '',
    developerId: developerId ? developerId : '',
  }
}

// 初始化表格
table = $('#table').bootstrapTable($.extend({}, tableConfig, {
  url: base + getReportDetailList,
  queryParams: function (params) {

    return $.extend({
      currentPage : params.pageNumber,
      pageSize    : params.pageSize,
      timerV : 1
    }, $('#searchForm').serializeObject(),jumpData)

  },
  ajax: function(params) {  //  自定义ajax
    console.log("params")
    console.log(params.data)
    $.ajax({
      headers     : header,
      url         : params.url,
      type        : params.type,
      contentType : params.contentType,
      data        : params.data
    })
      .done(function(res) {
        console.log(res)
        console.log("success")

        let totalAmount = $('.totalAmount'); //新增统计金额

        if(totalAmount.length == 0){

          let html = `<div class="pull-left totalAmount"><span class="amountTitle"></span><span class="amount">${(res.object.totalAmount/1000000).toFixed(2)}</span><span class="unit"> 万元</span></div>`;

          $('.fixed-table-pagination').before(html)

        }else {

          $('.totalAmount .amount').text(( res.object.totalAmount / 1000000).toFixed(2))
        }

        params.success({
          total: res.object.data.totalRows,
          rows: res.object.data.elements
        })
      })
      .fail(function(res) {
        console.log("error")
        console.log(res)

      })
      .always(function(res) {

        console.log("complete")

      });

  },
  columns: [
    {
      field: 'name',
      title: '客户姓名',
      valign: 'middle'
    }, {
      field: 'phone',
      title: '客户手机号',
      valign: 'middle'
    }, {
      field: 'propertyName',
      title: '楼盘名称',
      valign: 'middle'
    }, {
      field: 'propertyTypeName',
      title: '楼盘户型',
      valign: 'middle'
    }, {
      field: 'termId',
      title: '终端编号',
      valign: 'middle'
    }, {
      field: 'bankNum',
      title: '绑定手机银行卡号',
      valign: 'middle'
    }, {
      field: 'tradeAmount',
      title: '存款金额(万元)',
      valign: 'middle',
      formatter:(index, row) => {
        return (index / 1000000).toFixed(2)
      }
    }, {
      field: 'processStatus',
      title: '状态',
      valign: 'middle',
      formatter: (index, row) =>{
        if(index == 3 || index == 5 || index == 7|| index ==8 || index == 9){
          return  `<span class="success">办理成功</span>`
        }else if(index == 4 ){
          return  `<span class="fail">办理失败</span>`
        }else if(index == 1){
          return  `<span class="success">开户成功</span>`
        }else if (index == 2){
          return  `<span class="fail">开户失败</span>`
        }else if(index ==10){
          return  `<span class="success">转出成功</span>`
        }else if(index ==0){
          return `<span>创建订单</span>`
        }else {
          return `<span>未知</span>`
        }
      }
    }, {
      field: 'channel',
      title: '办理银行',
      valign: 'middle'
    }, {
      field: 'rawUpdateTime',
      title: '办理时间',
      valign: 'middle',
      formatter: (index, row) => {
        if (!index || index === 'null') {
          return ''
        }
        return moment(index).format('YYYY-MM-DD HH:mm:ss')
      }
    }, {
      field: 'action',
      valign: 'middle',
      align: 'center',
      title: '操作',
      formatter: function (index, row) {
        return `<div class="btn-group">
                      <button type="button" data-id="${ row.idStr }" class="btn btn-default btn-detail">查看详情</button>                  
                </div>`
      }
    }]
}))

table.on('load-success.bs.table', () => {
  $('.amountTitle').html('金额统计 : ')
})

// 初始化日期选择器
$('#operateStartDate').datetimepicker({
  format: "yyyy-mm-dd",
  startView: 3,
  minView: 2,
  autoclose: true
});
$('#operateEndDate').datetimepicker({
  format: "yyyy-mm-dd",
  startView: 3,
  minView: 2,
  autoclose: true
});

// 初始化银行
getBank();
// 初始化开发商
getDev();
// 动态加载楼盘列表
$('#developerId').on('change', () => {

  let devId = $('#developerId').children('option:selected').val();

  getBuild(devId);
})

function getBank() {

  $.ajax({
    headers: header,
    url: base + getChannelList
  })
    .done(function (res) {
      console.log("初始化银行 success")
      console.log(res)

      let channel = $('#channel'),
        html = '<option value="">请选择</option>',
        i = 0,
        data = res.object,
        len = data.length

      for (; i < len; i++) {
        html += `<option value="${ data[i].channelCode }">${ data[i].channelName }</option>`
      }

      channel.html(html)

    })
    .fail(function (res) {
      console.log(res)

      layer.msg('渠道银行失败', {
        icon: 5
      })

      console.log("error")
    })
    .always(function (res) {

      console.log("complete")
    })

}
function getDev() {

  $.ajax({
    headers:header,
    url: base + getDeveloperList
  })
    .done(function (res) {
      console.log(res)

      let code = res.code;

      if (code == 0) {
        console.log("获取开发商成功")

        let project = $('#developerId'),
          html = '<option value="">请选择</option>',
          i = 0,
          data = res.object,
          len = data.length;

        for (; i < len; i++) {
          html += `<option value="${ data[i].id }">${ data[i].enterInfo.enterpriseName }</option>`
        }

        project.html(html)
        project.selectize()
      } else {
        $('#devId').addClass('form-control')

        layer.msg('获取开发商失败', {
          icon: 5
        })
      }
    })
    .fail(function (res) {
      console.log(res)
      console.log("error")

    })
    .always(function (res) {
      console.log("complete")
    })
}
function getBuild(devId) {
  let data;

  if (devId) {
    data = {developersId: devId}
  } else {
    data = {}
  }

  $.ajax({
    headers: header,
    type: 'GET',
    url: base + getBuildingList,
    data: data
  })
    .done(function (res) {
      console.log(res)

      let code = res.code,
        project = $('#propertyId');

      if (code == 0) {
        console.log("获取楼盘成功")

        let html = '<option value="">请选择</option>',
          i = 0,
          data = res.object,
          len = data.length;

        for (; i < len; i++) {
          html += `<option value="${ data[i].id }">${ data[i].propertyName }</option>`
        }

        project.html(html)
      } else {
        project.html('<option value="">请选择</option>')
        layer.msg('获取楼盘失败', {
          icon: 5
        })
      }
    })
    .fail(function (res) {
      console.log(res)
      console.log("error")
      let project = $('#buildingId')
      project.html('<option value="">请选择</option>')

    })
    .always(function (res) {
      console.log("complete")
    })
}

// 搜索
$('#search-btn').on('click', (e) => {
  e.preventDefault();

  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage : 1,
    }, $('#searchForm').serializeObject())
  })
})

// 状态搜索
$("input[name = 'processStatusS']").on('change', (e) => {
  e.preventDefault();

  table.bootstrapTable('refresh', {
    query: $.extend({
      currentPage : 1,
    }, $('#searchForm').serializeObject())
  })
})

//跳转至详情页
$(document).on('click', '#table .btn-detail', (e) => {
  e.preventDefault()

  console.log('详情')

  let id = $(e.target).attr('data-id');
  window.location.href = './detail.html?id=' + id;
})